#include "rollcadresearchdialog.h"
#include "ui_rollcadresearchdialog.h"
#include <QTreeWidgetItem>
#include <QDebug>
#include <QModelIndex>
#include <QTreeWidget>
#include <QStringList>
#include <QSqlQuery>

RollCadreSearchDialog::RollCadreSearchDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::RollCadreSearchDialog)
{
    ui->setupUi(this);
    treeRender();
}

RollCadreSearchDialog::~RollCadreSearchDialog()
{
    delete ui;
}


void RollCadreSearchDialog::on_conditionTreeWidget_itemDoubleClicked(QTreeWidgetItem *item, int column)
{
    int index=ui->conditionTreeWidget->indexOfTopLevelItem(item);
    if(index>-1){
        return;
    }
    QString n = item->text(column);
    QString np= item->parent()->text(column);

    if(hash.contains(np)){
        if(!hash.value(np).contains(n)){
           hash[np]=QStringList()<<hash.value(np)<<n;
           new QTreeWidgetItem(treeitem,QStringList(n));
        }
    }else{
        hash[np]=QStringList(n);
        treeitem =new QTreeWidgetItem(ui->selectedTreeWidget,QStringList(np));
        new QTreeWidgetItem(treeitem,QStringList(n));
    }
    //设置选定树，项展开
    ui->selectedTreeWidget->expandAll();
}

void RollCadreSearchDialog::on_selectedTreeWidget_itemDoubleClicked(QTreeWidgetItem *item, int column)
{
    int index=ui->selectedTreeWidget->indexOfTopLevelItem(item);
    if(index>-1){
        return;
    }
    QString n = item->text(column);
    QString np= item->parent()->text(column);
    qDebug()<<item<<"---"<<(item->parent());
    qDebug()<<n<<"---"<<np;
    if(hash.value(np).size()==1){
        ui->selectedTreeWidget->removeItemWidget(item->parent(),0);
        delete item;
        delete item->parent();       
    }
    if(hash.value(np).size()>1){
        ui->selectedTreeWidget->removeItemWidget(item,0);
        delete item;
    }
    // 删除hash中的值
    QStringList list;
    foreach(QString v,hash.value(np)){
        if(v!=n){
            list << v;
        }
    }
    hash[np]=list;
    if(list.size()==0){
        hash.remove(np);
    }
}

void RollCadreSearchDialog::on_searchPushButton_clicked()
{
    // 获取界面上的元素值
    QStringList cadrename = QStringList()<< ui->nameLineEdit->text();
    hash["CadreName"]=cadrename;
    QStringList unit = QStringList()<< ui->unitLineEdit->text();
    hash["UnitName"] = unit;
    QStringList  postname= QStringList()<< ui->postNameLineEdit->text();
    hash["PostName"] = postname;
    QStringList  experpost= QStringList()<< ui->experpostLineEdit->text();
    hash["ExperPost"] = experpost;
    QStringList  experunit= QStringList()<< ui->experunitlineEdit->text();
    hash["ExperUnit"] = experunit;
    QStringList  school= QStringList()<< ui->schoolLineEdit->text();
    hash["School"] = school;
    QStringList  major= QStringList()<< ui->majorLineEdit->text();
    hash["Major"] = major;
    QStringList  workscholl= QStringList()<< ui->workschoolLineEdit->text();
    hash["WorkSchool"] = workscholl;
    QStringList  workmajor= QStringList()<< ui->workmajorLineEdit->text();
    hash["WorkMajor"] = workmajor;
    QStringList  familyunit= QStringList()<< ui->familyunitLineEdit->text();
    hash["FamilyUnit"] = familyunit;
    QStringList  familypro= QStringList()<< ui->familypostLineEdit->text();
    hash["FamilyPro"] = familypro;
    QStringList filerecv= QStringList()<< ui->fileRecvLineEdit->text();
    hash["FileNum"] = filerecv;
    QStringList orrelation= QStringList()<< (ui->orcheckBox->isChecked()?"1":"0");
    hash["OrRelation"] = orrelation;
    if(ui->nativegroupBox->isChecked()){
        QString  native= ui->nativePlaceLineEdit->text();
        QString nativecom= ui->nativecomboBox->currentText();
        hash["NativePlace"] = QStringList()<<nativecom<<native;
    }
    if(ui->birthgroupBox->isChecked()){
        QString  birthplace=  ui->birthPlaceLineEdit->text();
        QString  birthcom = ui->birthcomboBox_2->currentText();
        hash["Birthplace"] = QStringList()<<birthcom<<birthplace;
    }
    if(ui->growplacegroupBox->isChecked()){
        QString  growplace=  ui->growPlaceLineEdit->text();
        QString  growcom = ui->growcomboBox->currentText();
        hash["GrowPlace"] = QStringList()<<growcom<<growplace;
    }
    if(ui->birthgroupBox->isChecked()){
        QString  birthfrom=  ui->birthfromdateEdit->date().toString(QString("yyyy-MM-dd"));
        QString  birthto= ui->birthtodateEdit->date().toString(QString("yyyy-MM-dd"));
        hash["Birth"] = QStringList()<< birthfrom <<birthto;
    }
    if(ui->agegroupBox->isChecked()){
        QString  agefrom=  QString::number(ui->agefromspinBox->value());
        QString  ageto= QString::number(ui->agetospinBox->value());
        hash["age"] = QStringList()<< agefrom << ageto;
    }
    if(ui->joinworkgroupBox->isChecked()){
        QString  workfrom=  ui->workfromdateEdit->date().toString(QString("yyyy-MM-dd"));
        QString  workto= ui->worktodateEdit->date().toString(QString("yyyy-MM-dd"));
        hash["JoinWorkTime"] = QStringList()<< workfrom <<workto;
    }
    if(ui->partytimegroupBox->isChecked()){
        QString  partytimefrom=  ui->partytimefromdateEdit->date().toString(QString("yyyy-MM-dd"));
        QString  partytimeto= ui->partytimetodateEdit->date().toString(QString("yyyy-MM-dd"));
        hash["PartyTime"] = QStringList()<< partytimefrom <<partytimeto;
    }
    if(ui->worktimegroupBox->isChecked()){
        // 职务表里的任免时间(现任)，最早那个
        QString  worktimefrom=  ui->worktimefromdateEdit->date().toString(QString("yyyy-MM-dd"));
        QString  worktimeto= ui->worktimetodateEdit->date().toString(QString("yyyy-MM-dd"));
        hash["PostTime"] = QStringList()<< worktimefrom <<worktimeto;
    }
    if(ui->workyeargroupBox->isChecked()){
        // "已任职年限"
        QString  workyearfrom= QString::number(ui->workyearfromspinBox->value());
        QString  workyearto= QString::number(ui->workyeartospinBox->value());
        hash["PostYear"] = QStringList()<< workyearfrom <<workyearto;
    }
    if(ui->ranktimegroupBox->isChecked()){
        QString  ranktimefrom=  ui->ranktimefromdateEdit->date().toString(QString("yyyy-MM-dd"));
        QString  ranktimeto= ui->ranktimetodateEdit->date().toString(QString("yyyy-MM-dd"));
        hash["RankTime"] = QStringList()<< ranktimefrom <<ranktimeto;
    }
    if(ui->rankyeargroupBox->isChecked()){
        QString  rankyearfrom=  QString::number(ui->rankyearfromspinBox->value());
        QString  rankyearto= QString::number(ui->rankyeartospinBox->value());
        hash["RankYear"] = QStringList()<< rankyearfrom <<rankyearto;
    }
    if(ui->managestatusgroupBox->isChecked()){
        QString managestatus1 = ui->manageStatusCheckBox1->isChecked()?
                    QString::fromUtf8("在职"):QString();
        QString managestatus2 = ui->manageStatusCheckBox2->isChecked()?
                    QString::fromUtf8("离退"):QString();
        QString managestatus3 = ui->manageStatusCheckBox3->isChecked()?
                    QString::fromUtf8("其他"):QString();
        hash["ManageStatus"] = QStringList()<< managestatus1 <<managestatus2<<managestatus3;
    }
    if(ui->threeonegroupBox->isChecked()){
        QString threeone1 = ui->threeOneCheckBox1->isChecked()?
                    QString::fromUtf8("是"):QString();
        QString threeone2 = ui->threeOneCheckBox2->isChecked()?
                    QString::fromUtf8("否"):QString();
        hash["ThreeOne"] = QStringList()<< threeone1 <<threeone2;
    }
    // "年度考核"  check表  checkyear连续性判断
    QString checkyear = ui->checkCheckBox->isChecked()? "1": "0";
    hash["CheckYear"] = QStringList()<< checkyear;
    QString experiencenull = ui->experienceCheckBox->isChecked()?"1": "0";
    hash["ExperNull"] = QStringList()<< experiencenull;
//    qDebug()<< "---hash---"<< hash;
    RollCadreSearchResultDialog *resultDialog = new RollCadreSearchResultDialog(this);
    //关联信号和槽函数
    connect(this, SIGNAL(sendData(QHash<QString,QStringList>)), resultDialog,
            SLOT(receiveData(QHash<QString,QStringList>)));
    emit sendData(hash);
    resultDialog->initResultTable();
    resultDialog->exec();
    QDialog::reject();
}
void RollCadreSearchDialog::treeRender()
{
    QStringList sex;
    sex << trUtf8("男")<< trUtf8("女");
    treeYNItemRender(trUtf8("性别"),sex);
    treeItemRender(trUtf8("民族"),"NationCode","Nation");
    treeItemRender(trUtf8("政治面貌"),"PoliticCode","Politic");
    treeItemRender(trUtf8("职务级别"),"RankCode","RankName");
    treeItemRender(trUtf8("职务属性"),"PostCategoryCode","PostCategory");
    QStringList isfile;
    isfile << trUtf8("是")<< trUtf8("否");
    treeYNItemRender(trUtf8("已录数字档案"),isfile);
//    treeItemRender(trUtf8("档案类别"),"ArchiveClassCode","ClassName");
    treeItemRender(trUtf8("干部状态"),"ManageStatusCode","ManageStatus");
    treeItemRender(trUtf8("在职学历"),"EducationCode","Education");
    treeItemRender(trUtf8("在职学位"),"DegreeCode","Degree");
    treeItemRender(trUtf8("全日制学历"),"EducationCode","Education");
    treeItemRender(trUtf8("全日制学位"),"DegreeCode","Degree");
    treeItemRender(trUtf8("单位名称"),"unit","unitname");
    treeItemRender(trUtf8("单位层次"),"UnitGradationCode","UnitGradationName");
    treeItemRender(trUtf8("单位属性"),"UnitNatrueCode","UnitNatrueName");
    treeItemRender(trUtf8("单位性质"),"UnitCategoryCode","UnitCategory");
    treeItemRender(trUtf8("单位类别"),"UnitOfCategoryCode","UnitOfCategoryName");
    treeItemRender(trUtf8("单位级别"),"UnitLevelCode","UnitLevel");
    treeItemRender(trUtf8("单位隶属关系"),"AffiliationCode","AffiliationName");
}
void RollCadreSearchDialog::treeItemRender(QString pitem , QString table, QString name)
{
    QTreeWidgetItem *pro = new QTreeWidgetItem(ui->conditionTreeWidget);
    pro->setText(0, pitem);
    QSqlQuery query;
    query.exec(QString("select %1 from %2").arg(name,table));
    while (query.next()){
        QTreeWidgetItem *item = new QTreeWidgetItem(pro);
        item->setText(0, query.value(0).toString());
    }
}
void RollCadreSearchDialog::treeYNItemRender(QString pitem ,QStringList names)
{
    QTreeWidgetItem *pro = new QTreeWidgetItem(ui->conditionTreeWidget);
    pro->setText(0, pitem);
    foreach(QString name,names)
    {
        QTreeWidgetItem *item = new QTreeWidgetItem(pro);
        item->setText(0,name);
    }
}

void RollCadreSearchDialog::searchChild(QTreeWidgetItem *cItem, const QString &txt)
{
    int childCount = cItem->childCount();
    for  (int i = 0; i < childCount; ++i) {
        QTreeWidgetItem *item = cItem->child(i);
        if (-1 != item->text(0).indexOf(txt)) {
            item->setExpanded(true);
            item->setBackground(0,Qt::lightGray);
            parentExpand(item);
        } else {
            item->setBackground(0, m_itemBrush);
        }
        searchChild(item, txt);
    }
}
void RollCadreSearchDialog::parentExpand(QTreeWidgetItem *item)
{
    if (item->parent() != NULL) {
        QTreeWidgetItem *pItem = item->parent();
        if (! pItem->isExpanded()) {
            pItem->setExpanded(true);
        }
        parentExpand(pItem);
    }
}
void RollCadreSearchDialog::searchTree(QTreeWidget *treewidget,QString txt)
{
    treewidget->collapseAll();
    bool isEmptyTxt = txt.isEmpty();
    bool isEmptyTree = treewidget->topLevelItemCount(); //非零个为true
    if (isEmptyTxt) {
        QTreeWidgetItemIterator it(treewidget);
        while(*it) {
            (*it)->setBackground(0, m_itemBrush);
            it++;
        }
        return;
    }
    if ( ! isEmptyTree) {
        return;
    }
#if 0
    int count = treewidget->topLevelItemCount();
    for (int i =0; i < count; ++i) {
        QTreeWidgetItem *cItem = treewidget->topLevelItem(i);
        if (-1 != cItem->text(0).indexOf(txt)) {
            cItem->setBackground(0,Qt::lightGray);
        } else {
            cItem->setBackground(0, m_itemBrush);
        }
        searchChild(cItem, txt);
    }
#else
    QTreeWidgetItemIterator it(treewidget);
    while(*it) {
        QString str = (*it)->text(0);
        if (-1 != str.indexOf(txt)) {
            QTreeWidgetItem *pItem = (*it)->parent();
            if (pItem !=  NULL) {
                bool isExpanded = pItem->isExpanded();
                if (! isExpanded){
                    treewidget->expandItem(pItem);
                }
            }
            (*it)->setBackground(0,Qt::lightGray);
            parentExpand(*it);
        } else{
            (*it)->setBackground(0, m_itemBrush);
        }
        it++;
    }
#endif
}

void RollCadreSearchDialog::on_selectedpushButton_clicked()
{
    if(ui->selectedTreeWidget->topLevelItemCount()==0){
        return;
    }
    m_itemBrush =  ui->selectedTreeWidget->topLevelItem(0)->background(0);
    QString txt = ui->selectedLineEdit->text();
    searchTree(ui->selectedTreeWidget,txt);
}
void RollCadreSearchDialog::on_parampushButton_clicked()
{
     if(ui->conditionTreeWidget->topLevelItemCount()==0){
         return;
     }
     m_itemBrush =  ui->conditionTreeWidget->topLevelItem(0)->background(0);
     QString txt = ui->paramLineEdit->text();
     searchTree(ui->conditionTreeWidget,txt);
}

void RollCadreSearchDialog::on_samenamepushButton_clicked()
{
    RollCadreSearchResultDialog *resultDialog1 = new RollCadreSearchResultDialog(this);
    resultDialog1->initResultTable("",true);
    resultDialog1->exec();
    QDialog::reject();
}
